using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using DiscMaster.Web.Models;

namespace DiscMaster.Web.Areas.Courses.Controllers
{
    public class CoursesController : Controller
    {
        private IDiscMasterRepository repository;

        public CoursesController()
            : this(new DiscMasterRepository()){
        }

        public CoursesController(IDiscMasterRepository controllerrepository)
        {
            repository = controllerrepository;
        }

        //
        // GET: /Courses/

        [OutputCache(CacheProfile = "ShortCache", VaryByParam = "none")]
        public ActionResult Index()
        {
            var courses = repository.FindAllCourses().ToList();
            if (courses.Count==0)
            {
                return View("NoData");
            }
            else
            {
                return View("Index", courses);
            }
        }

        //
        // GET: /Courses/Details/name

        [OutputCache(CacheProfile = "MediumCache", VaryByParam = "id")]
        public ActionResult Details(string id)
        {
            if (!string.IsNullOrEmpty(id))
            {
                DiscMaster.Web.Models.Course course = repository.GetCourseByName(id);
                if (course == null)
                {
                    return View("NotFound");
                }
                return View("Details", course);
            }
            else
            {
                return View("NotFound");
            }
        }

        //
        // GET: /Courses/Forecast/5

        [OutputCache(CacheProfile = "OneHourCache", VaryByParam = "id")]
        public ActionResult Forecast(string courseid, int forecastindex)
        {
            var forecast = repository.GetForecast(courseid, forecastindex);
            if (forecast!=null)
            {
                return PartialView("Forecast", forecast);
            }
            else
            {
                return PartialView("ForecastNotFound");
            }
        }

        //
        // GET: /Courses/Create

        [Authorize()]
        public ActionResult Create()
        {
            var course = new DiscMaster.Web.Models.Course();
            return View(course);
        } 

        //
        // POST: /Courses/Create

        [Authorize()]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(DiscMaster.Web.Models.Course course)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    course.courseid = Guid.NewGuid();
                    UpdateModel(course);
                    if (repository.GetCourseByName(course.name) != null)
                    {
                        ModelState.AddModelError("name", "The specified name already exists");
                        return View(course);
                    }
                    course.createdby = repository.GetLoggedOnPlayer().UserId;
                    repository.AddCourse(course);

                    repository.Save();

                    return RedirectToAction("Details", new { id = course.name });
                }
                catch (Exception ex)
                {
                    ViewData["Error"] = ex.Message;
                    return View(course);
                }
            }
            return View(course);
        }

        //
        // GET: /Courses/CreateLayout/5

        [Authorize()]
        public ActionResult CreateLayout(string id)
        {
            var courselayout = new DiscMaster.Web.Models.CourseLayout();
            courselayout.Course = repository.GetCourse(id);
            return View(courselayout);
        }

        //
        // POST: /Courses/CreateLayout/5

        [Authorize()]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult CreateLayout(string id, FormCollection formcollection)
        {
            CourseLayout courselayout = new CourseLayout();
            courselayout.Course = repository.GetCourse(id);
            try
            {
                DiscMaster.Web.Models.Course course = repository.GetCourse(id);
                courselayout.layoutid = Guid.NewGuid();
                UpdateModel(courselayout, new[]{"name", "description"});

                if (repository.GetCourseLayoutByName(courselayout.name) != null)
                {
                    ModelState.AddModelError("name", "The specified name already exists");
                    return View(courselayout);
                }
                courselayout.courseid = course.courseid;
                for (int i = 1; i < int.Parse(formcollection.GetValue("numberofholes").AttemptedValue) + 1; i++)
                {
                    courselayout.Holes.Add(new DiscMaster.Web.Models.Hole(){holeid=Guid.NewGuid(), courseid=course.courseid, layoutid=courselayout.layoutid, number=i});
                }
                repository.AddCourseLayout(courselayout);

                repository.Save();

                return RedirectToAction("EditLayout", new { id = courselayout.layoutid });
            }
            catch (Exception ex)
            {
                ViewData["Error"] = ex.Message;
                return View(courselayout);
            }
        }
        //
        // GET: /Courses/Edit/5

        [Authorize()]
        public ActionResult EditLayout(string id)
        {
            var courselayout = repository.GetCourseLayout(id);
            if (courselayout == null)
            {
                return View("NotFound");
            }
            if (repository.GetLoggedOnPlayer().UserId != courselayout.Course.createdby)
            {
                return View("OnlyOwner");
            }
            return View(courselayout);
        }

        //
        // POST: /Courses/EditLayout/5

        [Authorize()]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult EditLayout(string id, FormCollection collection)
        {
            var courselayout = repository.GetCourseLayout(id);
            if (courselayout == null)
            {
                return View("NotFound");
            }
            if (repository.GetLoggedOnPlayer().UserId != courselayout.Course.createdby)
            {
                return View("OnlyOwner");
            }
            try
            {
                UpdateModel(courselayout);
                foreach (Hole hole in courselayout.Holes)
                {
                    UpdateModel(hole);
                }

                repository.Save();

                return RedirectToAction("Details", new { id = courselayout.Course.name });
            }
            catch
            {
                return View(courselayout);
            }
        }

        //
        // GET: /Courses/DeleteLayout/1
        [Authorize()]
        public ActionResult DeleteLayout(string id)
        {
            DiscMaster.Web.Models.Course course = repository.GetCourse(id);
            if (course == null)
                return View("NotFound");
            else
                return View(course);
        }

        //
        // POST: /Course/DeleteLayout/1
        [Authorize()]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult DeleteLayout(string id, string confirmButton)
        {
            DiscMaster.Web.Models.Course course = repository.GetCourse(id);
            if (course == null)
                return View("NotFound");
            repository.DeleteCourse(course);
            repository.Save();
            return View("DeletedLayout");
        }

        //
        // GET: /Courses/Edit/5

        [Authorize()]
        public ActionResult Edit(string id)
        {
            var course = repository.GetCourse(id);
            if (course == null)
            {
                return View("NotFound");
            }
            if (repository.GetLoggedOnPlayer().UserId != course.createdby)
            {
                return View("OnlyOwner");
            }
            return View(course);
        }

        //
        // POST: /Courses/Edit/5

        [Authorize()]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(string id, FormCollection collection)
        {
            DiscMaster.Web.Models.Course course = repository.GetCourse(id);
            if (course == null)
            {
                return View("NotFound");
            }
            if (repository.GetLoggedOnPlayer().UserId != course.createdby)
            {
                return View("OnlyOwner");
            }

            try
            {
                UpdateModel(course);

                repository.Save();

                return RedirectToAction("Details", new { id = course.courseid });
            }
            catch
            {
                return View(course);
            }
        }

        //
        // GET: /Courses/Delete/1
        [Authorize()]
        public ActionResult Delete(string id)
        {
            DiscMaster.Web.Models.Course course = repository.GetCourse(id);
            if (course == null)
                return View("NotFound");
            else
                return View(course);
        }

        //
        // POST: /Course/Delete/1
        [Authorize()]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Delete(string id, string confirmButton)
        {
            DiscMaster.Web.Models.Course course = repository.GetCourse(id);
            if (course == null)
                return View("NotFound");
            repository.DeleteCourse(course);
            repository.Save();
            return View("Deleted");
        }
    }
}
